package org.wit.ecommerce.service.impl;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.wit.ecommerce.dao.ProductDao;
import org.wit.ecommerce.domain.Product;
import org.wit.ecommerce.dto.Navigator;
import org.wit.ecommerce.service.IProductService;
import org.wit.ecommerce.util.PageNavigateCalculator;
/**
 * @spring.bean id="productService" parent="baseTransactionProxy" extends="true" transactionProxy="true"
 * @author Justin
 *
 */
public class ProductServiceImpl implements IProductService {
	private ProductDao productDao;
	
	@Override
	public Product getProductById(Long id) {
		return productDao.get(id);
	}

	@Override
	public void createProduct(Product product) {
		product.setCreateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		productDao.save(product);
	}

	@Override
	public void updateProduct(Product product) {
		productDao.save(product);
	}

	@Override
	public void deleteProduct(Product product) {
		productDao.delete(product);
	}

	@Override
	public Navigator<Product> getProductsByPage(int page, Map<String, ?> keywords) {
		PageNavigateCalculator pnc = new PageNavigateCalculator();
		pnc.setCurrentPage(page);
		pnc.setTotalRowsAmount(productDao.getTotalCount(keywords));
		int start = pnc.getCurrentPageRows();
		int limit = pnc.getPageSize();
		
		List<Product> products = productDao.findByPage(start, limit, keywords);
		Navigator<Product> navigator = new Navigator<Product>();
		navigator.setData(products);
		navigator.setNext(pnc.HasNext());
		navigator.setPageSize(pnc.getPageSize());
		navigator.setPrevious(pnc.HasPrevious());
		navigator.setTotalPages(pnc.getTotalPages());
		navigator.setTotalRowsAmount(pnc.getTotalRowsAmount());
		return navigator;
	}

	/**
	 * @spring.property ref="productDao"
	 * @param productDao
	 */
	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	@Override
	public void deleteProduct(Long id) {
		productDao.delete(id);
	}
}
